﻿// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System.Collections.ObjectModel;
using System.Linq;
using Rachmans.Sabang.Model;

namespace Rachmans.Sabang.Data
{
    public class BookmarkCollection : ObservableCollection<Bookmark>
    {
        // Data context for the local database
        private BookmarkContext bookmarkDB;

        public BookmarkCollection()
            : base()
        {
            // Connect to the database and instantiate data context.
            bookmarkDB = new BookmarkContext(BookmarkContext.DBConnectionString);

            // Define the query to gather all of the to-do items.
            var bookmarksInDB = from Bookmark bookmark in bookmarkDB.Bookmarks
                                orderby bookmark.DtmSave descending
                                select bookmark;

            // Execute the query and place the results into a collection.
            foreach (Bookmark b in bookmarksInDB)
            {
                Add(b);
            }
        }

        protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            base.OnCollectionChanged(e);

            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
                bookmarkDB.Bookmarks.DeleteOnSubmit(e.OldItems[0] as Bookmark);
                bookmarkDB.SubmitChanges();
            }
        }
    }
}
